import { defineStore } from "pinia"
import { ref, computed } from "vue"
import type { Job, Filter } from "../types"

export const useJobsStore = defineStore("jobs", () => {
  const jobs = ref<Job[]>([
    {
      id: "1",
      title: "AI服务代理商",
      company: "智能科技",
      location: "上海",
      salary: "50000-80000元/月",
      experience: "5-10年",
      education: "本科",
      type: "兼职",
      description: "负责AI服务推广和客户维护",
      requirements: "具备相关行业经验",
      benefits: ["五险一金", "年终奖"],
      status: "active",
      views: 88,
      communications: 11,
      interested: 2,
      createdAt: "2024-06-12",
      expiresAt: "2025-07-12",
      urgent: true,
    },
    {
      id: "2",
      title: "AI营销市场合伙人",
      company: "创新科技",
      location: "上海",
      salary: "50-80K·15薪",
      experience: "5-10年",
      education: "本科",
      type: "全职",
      description: "负责AI营销策略制定和执行",
      requirements: "具备市场营销经验",
      benefits: ["五险一金", "年终奖", "股权激励"],
      status: "active",
      views: 304,
      communications: 65,
      interested: 12,
      createdAt: "2024-06-11",
      expiresAt: "2025-07-11",
      urgent: true,
    },
  ])

  const filters = ref<Filter>({})
  const searchQuery = ref("")

  const filteredJobs = computed(() => {
    let result = jobs.value

    if (searchQuery.value) {
      result = result.filter((job) => job.title.includes(searchQuery.value) || job.company.includes(searchQuery.value))
    }

    if (filters.value.location?.length) {
      result = result.filter((job) => filters.value.location!.includes(job.location))
    }

    if (filters.value.experience?.length) {
      result = result.filter((job) => filters.value.experience!.includes(job.experience))
    }

    return result
  })

  const addJob = (job: Omit<Job, "id" | "views" | "communications" | "interested" | "createdAt">) => {
    const newJob: Job = {
      ...job,
      id: Date.now().toString(),
      views: 0,
      communications: 0,
      interested: 0,
      createdAt: new Date().toISOString().split("T")[0],
    }
    jobs.value.push(newJob)
  }

  const updateJob = (id: string, updates: Partial<Job>) => {
    const index = jobs.value.findIndex((job) => job.id === id)
    if (index !== -1) {
      jobs.value[index] = { ...jobs.value[index], ...updates }
    }
  }

  const deleteJob = (id: string) => {
    const index = jobs.value.findIndex((job) => job.id === id)
    if (index !== -1) {
      jobs.value.splice(index, 1)
    }
  }

  const setFilters = (newFilters: Filter) => {
    filters.value = newFilters
  }

  const setSearchQuery = (query: string) => {
    searchQuery.value = query
  }

  return {
    jobs,
    filters,
    searchQuery,
    filteredJobs,
    addJob,
    updateJob,
    deleteJob,
    setFilters,
    setSearchQuery,
  }
})
